package com.example.st.service.impl;

import com.example.st.common.ResponseResult;
import com.example.st.dao.UserRepository;
import com.example.st.entity.User;
import com.example.st.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public ResponseResult<List<User>> getAllUsers(Long requesterUid) {
        Optional<User> userOptional = userRepository.findById(requesterUid);
        if (userOptional.isPresent() && userOptional.get().getRole() == 0) {
            List<User> userList = userRepository.findAll();
            return new ResponseResult<>(200, "Success", userList);
        }
        return new ResponseResult<>(401, "Unauthorized", null);
    }

    @Override
    public ResponseResult<User> getUserById(Long requesterUid, Long targetUid) {
        Optional<User> requesterOptional = userRepository.findById(requesterUid);
        if (requesterOptional.isPresent()) {
            User requester = requesterOptional.get();
            if (requester.getRole() == 0 || requester.getUid().equals(targetUid)) {
                Optional<User> userOptional = userRepository.findById(targetUid);
                if (userOptional.isPresent()) {
                    return new ResponseResult<>(200, "Success", userOptional.get());
                } else {
                    return new ResponseResult<>(404, "User not found", null);
                }
            }
        }
        return new ResponseResult<>(401, "Unauthorized", null);
    }

    @Override
    public ResponseResult<User> createUser(Long requesterUid, User user) {
        Optional<User> userOptional = userRepository.findById(requesterUid);
        if (userOptional.isPresent() && userOptional.get().getRole() == 0) {
            String encryptedPassword = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
            user.setPassword(encryptedPassword);
            User createdUser = userRepository.save(user);
            return new ResponseResult<>(200, "User created", createdUser);
        }
        return new ResponseResult<>(401, "Unauthorized", null);
    }

    @Override
    public ResponseResult<User> updateUser(Long requesterUid, Long targetUid, User userDetails) {
        Optional<User> requesterOptional = userRepository.findById(requesterUid);
        if (requesterOptional.isPresent()) {
            User requester = requesterOptional.get();
            if (requester.getRole() == 0 || requester.getUid().equals(targetUid)) {
                Optional<User> userOptional = userRepository.findById(targetUid);
                if (userOptional.isPresent()) {
                    User existingUser = userOptional.get();
                    // 仅更新传递的字段
                    if (userDetails.getName() != null) {
                        existingUser.setName(userDetails.getName());
                    }
                    if (userDetails.getPassword() != null) {
                        String encryptedPassword = DigestUtils.md5DigestAsHex(userDetails.getPassword().getBytes());
                        existingUser.setPassword(encryptedPassword);
                    }
                    if (userDetails.getRole() != null) {
                        existingUser.setRole(userDetails.getRole());
                    }
                    User updatedUser = userRepository.save(existingUser);
                    return new ResponseResult<>(200, "User updated", updatedUser);
                } else {
                    return new ResponseResult<>(404, "User not found", null);
                }
            }
        }
        return new ResponseResult<>(401, "Unauthorized", null);
    }

    @Override
    public ResponseResult<Void> deleteUser(Long requesterUid, Long targetUid) {
        Optional<User> requesterOptional = userRepository.findById(requesterUid);
        if (requesterOptional.isPresent() && requesterOptional.get().getRole() == 0) {
            userRepository.deleteById(targetUid);
            return new ResponseResult<>(200, "User deleted", null);
        }
        return new ResponseResult<>(401, "Unauthorized", null);
    }

    @Override
    public ResponseResult<Void> registerUser(User user) {
        try {
            // Encrypt password using MD5
            String encryptedPassword = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
            user.setPassword(encryptedPassword);
            userRepository.save(user);
            return new ResponseResult<>(200, "User registered successfully", null);
        } catch (Exception e) {
            return new ResponseResult<>(500, "Failed to register user", null);
        }

    }

    @Override
    public ResponseResult<Long> authenticateUser(String account, String password) {

        try {
            User user = userRepository.findByAccount(account);
            if (user != null) {
                String encryptedPassword = DigestUtils.md5DigestAsHex(password.getBytes());
                if (user.getPassword().equals(encryptedPassword)) {
                    return new ResponseResult<>(200, "Login successful", user.getUid());
                } else {
                    return new ResponseResult<>(401, "Incorrect password", null);
                }
            } else {
                return new ResponseResult<>(404, "User not found", null);
            }
        } catch (Exception e) {
            return new ResponseResult<>(500, "Internal server error", null);
        }
    }
}

